use crate::{
    auth::AuthService,
    AppError, AppResult, PageResult, QueryParams, User, UserStatus,
};
use chrono::Utc;
use std::collections::HashMap;
use std::sync::Mutex;
use uuid::Uuid;

// 内存中的用户数据存储
lazy_static::lazy_static! {
    static ref USERS: Mutex<HashMap<String, User>> = Mutex::new(HashMap::new());
}

// 初始化示例用户数据
fn init_sample_users() {
    let mut users = USERS.lock().unwrap();
    
    // 添加示例用户
    let sample_users = vec![
        User {
            id: "user_001".to_string(),
            username: "zhangsan".to_string(),
            nickname: "张三".to_string(),
            email: Some("zhangsan@example.com".to_string()),
            phone: Some("13800138001".to_string()),
            avatar: None,
            status: UserStatus::Active,
            role_ids: vec!["user".to_string()],
            dept_id: Some("1".to_string()),
            dept_name: Some("技术部".to_string()),
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
            last_login_time: Some(Utc::now() - chrono::Duration::hours(2)),
        },
        User {
            id: "user_002".to_string(),
            username: "lisi".to_string(),
            nickname: "李四".to_string(),
            email: Some("lisi@example.com".to_string()),
            phone: Some("13800138002".to_string()),
            avatar: None,
            status: UserStatus::Active,
            role_ids: vec!["user".to_string()],
            dept_id: Some("2".to_string()),
            dept_name: Some("销售部".to_string()),
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
            last_login_time: Some(Utc::now() - chrono::Duration::hours(5)),
        },
        User {
            id: "user_003".to_string(),
            username: "wangwu".to_string(),
            nickname: "王五".to_string(),
            email: Some("wangwu@example.com".to_string()),
            phone: Some("13800138003".to_string()),
            avatar: None,
            status: UserStatus::Inactive,
            role_ids: vec!["user".to_string()],
            dept_id: Some("1".to_string()),
            dept_name: Some("技术部".to_string()),
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
            last_login_time: Some(Utc::now() - chrono::Duration::days(2)),
        },
    ];
    
    for user in sample_users {
        users.insert(user.id.clone(), user);
    }
}

#[tauri::command]
pub async fn get_user_list(params: QueryParams) -> AppResult<PageResult<User>> {
    // 初始化示例数据
    init_sample_users();
    
    let users = USERS.lock().unwrap();
    let mut user_list: Vec<User> = users.values().cloned().collect();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            user_list.retain(|user| {
                user.username.contains(keyword) ||
                user.nickname.contains(keyword) ||
                user.email.as_ref().map_or(false, |email| email.contains(keyword)) ||
                user.phone.as_ref().map_or(false, |phone| phone.contains(keyword))
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            let status_value: i32 = status.parse().unwrap_or(0);
            user_list.retain(|user| {
                let user_status: i32 = user.status.clone().into();
                user_status == status_value
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &user_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn create_user(mut user: User) -> AppResult<User> {
    // 验证必填字段
    if user.username.is_empty() {
        return Err(AppError::ValidationError("用户名不能为空".to_string()));
    }
    
    if user.nickname.is_empty() {
        return Err(AppError::ValidationError("昵称不能为空".to_string()));
    }
    
    // 检查用户名是否已存在
    let users = USERS.lock().unwrap();
    if users.contains_key(&user.username) {
        return Err(AppError::ValidationError("用户名已存在".to_string()));
    }
    
    // 设置用户ID和时间
    user.id = Uuid::new_v4().to_string();
    user.create_time = Utc::now();
    user.update_time = Utc::now();
    
    // 保存用户
    let mut users = USERS.lock().unwrap();
    users.insert(user.id.clone(), user.clone());
    
    Ok(user)
}

#[tauri::command]
pub async fn update_user(mut user: User) -> AppResult<User> {
    let mut users = USERS.lock().unwrap();
    
    if let Some(existing_user) = users.get_mut(&user.id) {
        // 更新字段
        existing_user.nickname = user.nickname;
        existing_user.email = user.email;
        existing_user.phone = user.phone;
        existing_user.avatar = user.avatar;
        existing_user.status = user.status;
        existing_user.role_ids = user.role_ids;
        existing_user.dept_id = user.dept_id;
        existing_user.dept_name = user.dept_name;
        existing_user.update_time = Utc::now();
        
        Ok(existing_user.clone())
    } else {
        Err(AppError::NotFoundError("用户不存在".to_string()))
    }
}

#[tauri::command]
pub async fn delete_user(user_id: String) -> AppResult<()> {
    let mut users = USERS.lock().unwrap();
    
    if users.remove(&user_id).is_some() {
        Ok(())
    } else {
        Err(AppError::NotFoundError("用户不存在".to_string()))
    }
}

#[tauri::command]
pub async fn update_user_status(user_id: String, status: i32) -> AppResult<()> {
    let mut users = USERS.lock().unwrap();
    
    if let Some(user) = users.get_mut(&user_id) {
        user.status = status.into();
        user.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("用户不存在".to_string()))
    }
}

#[tauri::command]
pub async fn get_user_by_id(user_id: String) -> AppResult<User> {
    let users = USERS.lock().unwrap();
    
    users
        .get(&user_id)
        .cloned()
        .ok_or_else(|| AppError::NotFoundError("用户不存在".to_string()))
}

#[tauri::command]
pub async fn reset_user_password(user_id: String, new_password: String) -> AppResult<()> {
    // 这里应该实现密码重置逻辑
    // 目前只是模拟成功
    Ok(())
}

#[tauri::command]
pub async fn export_users() -> AppResult<Vec<User>> {
    let users = USERS.lock().unwrap();
    Ok(users.values().cloned().collect())
}
